layui.use(['jquery', 'form', 'layer'], function () {
    var $ = layui.jquery,
        form = layui.form,
        layer = layui.layer;

    //验证
    form.verify({
        userName: function (value, item) {
            if (value.length < 1) {
                return '用户名不能为空';
            }
            if (!new RegExp("(^([\u0391-\uFFE5]|[a-zA-Z0-9]|[._-]){2,15}$)").test(value)) {
                return '用户名不合法(允许为2-15位汉字、字母、数字、"."、"-"、"_")';
            }
            if(/(^\_)|(\__)|(\_+$)/.test(value)){
                return '用户名首尾不能出现下划线\'_\'';
            }
        },
        password: [
            /^[\S]{5,20}$/
            ,'密码必须5到20位，且不能出现空格'
        ],
        validation: function (value) {
            /*if (value.length < 1) {
                return '邮箱不能为空';
            }*/
        }
    });

    $('.form_swap-link').click(function () {
        $('.main').toggleClass('form-card-flipped');
    });

    //登录按钮事件
    form.on('submit(btnLogin)', function(data){
        $.ajax({
            async: false,
            type: "POST",
            url: "/user/login",
            data: data.field,
            dataType: 'json',
            beforeSend:function(){
                layer.load(1);
            },
            success: function (res) {
                setTimeout(function(){
                    layer.closeAll('loading');
                    if (res.success) {
                        layer.msg('认证成功！', {icon: 6, time: 1200});
                        setTimeout(function(){
                            location.href = "/to_index";
                        }, 1500);
                    } else {
                        layer.msg(res.statusMessage, {icon: 5, time: 2000});
                    }
                }, 1000);
            },
            error: function (res) {
                layer.closeAll('loading');
                layer.msg(res.statusMessage, {icon: 5, time: 2000});
            }
        });
        return false;
    });

    form.on('submit(btnReg)', function(data){
        layer.msg(JSON.stringify(data.field));
        return false;
    });
});
